package com.feifan.monthhelper.utils;

import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;

import android.support.annotation.ColorInt;
import android.support.annotation.IntRange;
import android.support.annotation.Size;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SpannableUtils {
    private SpannableString ss;
    @ColorInt
    private int keyWordColor;

    private SpannableUtils(String text) {
        ss = new SpannableString(text);
    }

    public static SpannableUtils init(String text) {
        return new SpannableUtils(text);
    }

    public SpannableUtils setKeyWordColor(@ColorInt int color) {
        this.keyWordColor = color;
        return this;
    }

    public SpannableUtils changeColor(@Size(min = 1) String keyWord) {
        String string = ss.toString().toLowerCase();
        String key = keyWord.toLowerCase();

        Pattern pattern = Pattern.compile(key);
        Matcher matcher = pattern.matcher(string);

        while (matcher.find()) {
            int start = matcher.start();
            int end = matcher.end();
            ss.setSpan(new ForegroundColorSpan(keyWordColor), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return this;
    }

    public SpannableUtils changeColor(@IntRange(from = 0) int startIndex, int endIndex) {
        ss.setSpan(new ForegroundColorSpan(keyWordColor), startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return this;
    }

    public SpannableString get() {
        return ss;
    }
}
